from django.http import JsonResponse

class ApiResponse:
    def __init__(self, status, code, message, data=None, errors=None):
        """
        初始化 API 响应
        :param status: 请求处理结果，'success' 或 'error'
        :param code: HTTP 状态码，如 200, 400, 404 等
        :param message: 响应的简短消息
        :param data: (可选) 成功时返回的数据
        :param errors: (可选) 错误时返回的详细信息，默认为 None
        """
        self.status = status
        self.code = code
        self.message = message
        self.data = data or {}
        self.errors = errors or None  # 如果没有错误，则默认为 None

    def get_response(self):
        """
        构建并返回标准的 JSON 响应
        :return: JsonResponse 对象
        """
        # 构建基础响应字典
        response = {
            "status": self.status,
            "code": self.code,
            "message": self.message,
            "data": self.data
        }

        # 如果存在错误，则添加 errors 字段
        if self.errors is not None and len(self.errors) > 0:
            response["errors"] = self.errors

        return JsonResponse(response, status=self.code)

# 定义成功响应
def success_response(data, message="Request was successful"):
    return ApiResponse(
        status="success",
        code=200,
        message=message,
        data=data
    ).get_response()

# 定义错误响应
def error_response(code, message, errors=None):
    return ApiResponse(
        status="error",
        code=code,
        message=message,
        errors=errors or []
    ).get_response()

def traffic_control_response():
    return ApiResponse(
        status="success",
        code=429,
        message="There are too many people trying at the moment.",
    )